
import os
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

import logging

context = None

def init(context_):
    global context
    context = context_


class ActionUpdateFolder:
    def __init__(self, node):
        self.node = node
    def updateFolder(self, obj):
        global context
        data_service = context.find_service("DataService")

        str_resource_path = self.node.get_prop("url")

        nodes_list = self.node.get_children()
        for resource in nodes_list:
            resource.delete()

        url2node = {}
        url2node[str_resource_path] = self.node

        for root,dirs,files in os.walk(str_resource_path):
            if root not in url2node:
                print(root)
                print(url2node)
                continue
            
            for dir_p in dirs:
                str_dir = os.path.join(root,dir_p)
                new_node = data_service.create_node("Dir", dir_p)
                new_node.set_prop('url', str_dir)
                url2node[root].add_child(new_node)
                url2node[str_dir] = new_node
            for file_p in files:
                str_file = os.path.join(root,file_p)
                new_node = data_service.create_node("File", file_p)
                new_node.set_prop('url', str_file)
                url2node[root].add_child(new_node)


class UIMainFileMenu:
    def __init__(self):
        self._file = None
    def priorty(self):
        return 1000
    def add_menu(self, menu_bar):
        self.file_menu = menu_bar.addMenu("File")

        self.action0 = QAction("打开文件夹")
        self.action0.triggered.connect(self.openFolder)
        self.file_menu.addAction(self.action0)

    def add_toolbar(self, toolBar):
        pass

    def openFolder(self, obj):
        global context

        logging.info("open Folder")

        dir_select = QFileDialog.getExistingDirectory(None, "文件夹选择", "文件夹选择")
        if not dir_select:
            return 

        data_service = context.find_service("DataService")
        root_node =  data_service.root_node()
        if root_node:
            data_service.close()

        data_service.create_rootnode(os.path.basename(dir_select))
        # 设置属性
        root_node =  data_service.root_node()
        if not root_node:
            return 
        
        root_node.set_prop("url", dir_select)

        # 更新文件
        action = ActionUpdateFolder(root_node)
        action.updateFolder(root_node)

        context.fire('event::Project::Open', root_node)
        

class ActionNewNode:
    def __init__(self, parent_node):
        self._parent = parent_node
    def on_add_folder(self, obj):
        # 提示输入名称
        text, ok = QInputDialog().getText(None, "输入文件夹名称", "名称:", QLineEdit.Normal)
        if not (ok and text):
            return

        # 新建文件夹节点
        try:
            parent_url = self._parent.get_prop("url")
            url = parent_url + "\\" + text
            os.makedirs(url)
            
            global context
            data_service = context.find_service("DataService")

            print(data_service)
            new_node = data_service.create_node("Dir", text)
            print(new_node)

            new_node.set_prop("url", url)

            print(url)
            self._parent.add_child(new_node)
        except BaseException as e:
            print(e)

        

    def on_add_file(self, obj):
        # 提示输入名称
        text, ok = QInputDialog().getText(None, "输入文件名称", "名称:", QLineEdit.Normal)
        if not (ok and text):
            return           

        # 新建文件夹节点
        try:
            parent_url = self._parent.get_prop("url")
            url = parent_url + "\\" + text
            with open(url, "w") as fp:
                pass
           
            global context
            data_service = context.find_service("DataService")
            new_node = data_service.create_node("File", text)
            new_node.set_prop("url", url)
            self._parent.add_child(new_node)
        except BaseException as e:
            print(e)
   

class DataExploreBasicOpMenu:
    def __init__(self):
        self.menus = []

    def priorty(self):
        return 1000

    def add_menu(self, menu, nodes):
        self.menus = []      
        if len(nodes) != 1:
            return 

        # 新建文件夹
        # 新建文件
        node = nodes[0]
        kind = node.get_kind()

        if (kind == "Dir"):
            action = menu.addAction("新建文件夹")
            obj = ActionNewNode(node)
            self.menus.append(obj)
            action.triggered.connect(obj.on_add_folder)

            action = menu.addAction("新建文件")
            obj = ActionNewNode(node)
            self.menus.append(obj)
            action.triggered.connect(obj.on_add_file)

         
config = {
    'pluginid': 'AIDE::UI::Menu',
    # 菜单扩展
    #  文件|新建  文件|打开   文件|保存   文件|另存为   文件|关闭
    # 工具条扩展
    #    新建  打开  保存  另存为  关闭 | 新建页面
    "extensions" : [
        {
            "name": "PL::Basic::Menu",
            "id": "UIPrototype::Basic::Menu::OpenSave",
            "impl": UIMainFileMenu()
        },

        {

            "name": 'PL::DataExplore::Menu',

            'id': 'PL::DataExplore::Menu::IDE::BasicOp',

            'impl': DataExploreBasicOpMenu()

        }
    ],
    "subscribes" : [
    ]
}